/*
 * Copyright (C) 2008 GeoScheduler team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.android.activities;


import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.geoscheduler.android.R;
import org.geoscheduler.android.tools.DBHelper;
import org.geoscheduler.android.tools.DateTimeHelper;
import org.geoscheduler.android.tools.FormatHelper;
import org.geoscheduler.android.tools.GSMenuBuilder;
import org.geoscheduler.model.Event;
import org.geoscheduler.model.Tag;

import android.app.ListActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

/**
 * ListEvents Activity of GeoScheduler client application
 * 
 * @author paja
 */
public class ListEvents extends ListActivity {
	
	private static final int DBCHANGE = 5434;
	
	protected ListView eventsList;
	
	protected ImageButton btnNew;
	
	protected ImageButton btnSearch;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);	
		
		initView();
		
		refillList();
	}
	
	protected void initView() {
		setContentView(R.layout.listevents);
		
		eventsList = (ListView) findViewById(android.R.id.list);
		eventsList.setDividerHeight(0);		
		
		btnSearch = (ImageButton) findViewById(R.id.le_search_button);
		btnNew = (ImageButton) findViewById(R.id.le_new_button);
		
		setListeners();
	}
	
	/**
	 * Takes care of setting up all ListEvents listeners
	 */
	protected void setListeners() {

		/* New button click listener */
		btnNew.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				newEvent();
			}
		});

		btnSearch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				Toast.makeText(ListEvents.this, R.string.msg_not_implemented, Toast.LENGTH_SHORT).show();
			}
		});		
	}

	/**
	 * Starts activity to create new Event
	 */
	protected void newEvent() {
		Intent editEvent = new Intent();
        editEvent.setClassName("org.geoscheduler.android", "org.geoscheduler.android.activities.EditEvent");
        startActivityForResult(editEvent, DBCHANGE);
	}
	
	/**
	 * Refill listview with no filter
	 */
	@SuppressWarnings("unchecked")
	protected void refillList() {
		List data = getEventsData();
		setListAdapter(
				new SimpleAdapter(this, data,
                R.layout.listitem, 
                new String[] { "title", "date", "tags", "alertType" },
                new int[] { R.id.li_title, R.id.li_date, R.id.li_tags, R.id.li_alerttype }));
		
		eventsList.setSelection(0);		
		eventsList.requestFocus();
	}
	
	/**
	 * Get dataset for listview
	 */
	@SuppressWarnings("unchecked")
	protected List getEventsData() {

		SQLiteDatabase db = DBHelper.openDB(this);
		List<Event> items = (List) DBHelper.fetchAllInsts(db, new Event());
		
		List data = new ArrayList();
		for (Event event: items) {
			
			List<Tag> tags = DBHelper.fetchTags(db, event.getId());
			
			Map item = new Hashtable();
			item.put("title", event.getTitle());
			item.put("id", event.getId());
			
			String date = DateTimeHelper.getDateToString(event.getAlertTypeEnum(), event.getTimeFrom(),	event.getTimeTo());
			if ((date == null) || ("".equals(date.trim()))) {
				item.put("date", getText(R.string.label_anytime));
			} else {
				item.put("date", date);
			}
			
			if ((tags != null) && (!tags.isEmpty())) {
				item.put("tags", FormatHelper.formatTags(tags));
			} else {
				item.put("tags", "");
			}
			
			item.put("alertType", String.valueOf(event.getAlertType()));
			
			data.add(item);
	
		}
		db.close();
		
		return data;
	}
	
	/**
	 * Item click listener redirects to detailed view of selected event
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
	 */
	@Override
	@SuppressWarnings("unchecked")
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Map map = (Map) l.getItemAtPosition(position);

        long eventId = (Long) map.get("id");
        
        Intent editEvent = new Intent();
        editEvent.setClassName("org.geoscheduler.android", EditEvent.class.getName());
        editEvent.putExtra("org.geoscheduler.android.item.id", eventId);

        startActivityForResult(editEvent, DBCHANGE);
    }
	
	/**
	 * Operations for finished subactivity
	 * 
	 * @see android.app.Activity#onActivityResult(int, int, java.lang.String, android.os.Bundle)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
		if (requestCode == DBCHANGE) {
			refillList();
		}
    }

	/**
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		return GSMenuBuilder.createOptionsMenu(menu, this,
								GSMenuBuilder.Item.SHOW_MAPOVERVIEW,
								GSMenuBuilder.Item.SETUP,
								GSMenuBuilder.Item.LOGIN,
								GSMenuBuilder.Item.SERVICES_START,
								GSMenuBuilder.Item.SERVICES_STOP);
	}

	/**
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		
		return GSMenuBuilder.menuItemSelected(this, item);
	}
}